import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;//IP地址
    private int serverPort;//端口

    //客户端启动，需要知道服务器在哪里
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        /*对于客户端来说不需要显示关联端口。就好像来餐厅吃饭的顾客不需要每次都坐在同一个位置
        * 但是不代表没有端口，而是系统自动分配了个空闲端口*/
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            //1、先从控制台读取一个字符过来
            //先打印一个提示符，提示用户要输入内容
            System.out.println("——>");
            String request = scanner.next();
            //2、把字符串构造成UDP packet并进行发送
            /*就好像把信件装进信封并进行发送一样*/
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //3、客户端尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4、把响应数据转换成String显示出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("发送的数据:%s,接收的数据:%s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
